#include <QDebug>
#include <QProcess>
#include <windows.h>
#include <QDir>
#include <QTimer>
#include <QMessageBox>
#include "myApplication.h"
#include "worker.h"
#include "usbdevice.h"

worker::worker(QObject *parent) :
    QThread(parent)
{
    perVal = 0;
    timer = new QTimer(this);
    timer->setInterval(4000);
    timer->setSingleShot(false);
    connect(timer,SIGNAL(timeout()),this,SLOT(timeoutAction()));
}

void worker::timeoutAction()
{
    qDebug() << "time out";
    if ((perVal < 100) && (perVal > 0))
    {
        perVal = perVal + 5;
        emit doingPercent(QVariant(this->index), QVariant(perVal));
    }
    if (perVal >= 100)
    {
        timer->stop();
    }
}

void worker::run()
{
    qDebug() << "I'm Running";
    perVal = 2;
    //emit doingPercent(QVariant(this->index), QVariant(20));
    formatDev2Fat32(disk, label);
    //emit doingPercent(QVariant(this->index), QVariant(40));
    copyFiles2Disk(disk, "clonezilla");
    //emit doingPercent(QVariant(this->index), QVariant(90));
    makeDeviceBootable(disk);
    perVal = 100;
    emit doingPercent(QVariant(this->index), QVariant(100));

}

void worker::formatDev2Fat32(QString disk, QString labelName)
{
    QProcess process;

    qDebug() << "format start";
    QString fmtString = QString("format %1 /U /V:%2 /FS:fat32 /q /y").arg(disk).arg(labelName);
    system(fmtString.toLatin1().data());
    // process.execute(QString("format D: /FS:fat32 /q "));

    //ShellExecute(NULL,L"open",L"format D: /FS:fat32 /q /y",NULL,NULL, SW_SHOW );
    qDebug() << "format over:" << fmtString;
}

void worker::copyFiles2Disk(QString disk, QString filePath)
{
    QProcess process;
    qDebug() << "Copying files...";
    Sleep(1000);
    QString fmtString = QString("xcopy %1 %2 /e").arg(filePath).arg(disk);

     //system(fmtString.toLatin1().data());
    process.execute(fmtString);
    qDebug() << "Copy file end:" << fmtString << ";" << QDir::currentPath();
}

void worker::makeDeviceBootable(QString disk)
{
    QProcess process;
    qDebug() << "Making device bootable...";
    QString fmtString = QString("%1syslinux.exe -d syslinux -mafi %1").arg(disk);

     //system(fmtString.toLatin1().data());
    process.execute(fmtString);
    qDebug() << "Make device bootable end:" << fmtString;
}
